import Taro from '@tarojs/taro';

import {
  Command,
  GAME_TYPE,
  GAME_STORAGE_INFO,
  RANKING_TYPE,
  PROP_STAUTS,
  GAME_RPICE_TYPE,
  PROP_TYPE,
} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';

import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async status() {
      // 或取当前状态值
      let {
        main: {isLoading},
      } = getData();
      action.commonChange('main.isLoading', !isLoading);
    },

    /**
     * 查询用户信息
     */
    async loadUserInfo(payload) {
      console.log('action.ts loadUserInfo payload', payload);

      // action.commonChange('main.userInfo', {});
      action.commonChange('main.response.loadUser', '');
      action.commonChange('main.status.loadingUser', true);

      let {data, code, message} = await api.customerBaseController.findCustomerBaseInfoForGame({});
      let userInfo: any = data || null;
      if (!userInfo) {
        userInfo = Taro.getStorageSync(GAME_STORAGE_INFO);
      }
      let accountType = '';
      if (userInfo && userInfo.customerName) {
        // 判断是否是会员
        if (!userInfo.isAquamarineMember && !userInfo.isCrystalMember) {
          accountType = '';
        } else if (userInfo.isAquamarineMember && userInfo.isCrystalMember) {
          accountType = 'isAquamarineMember&isCrystalMember';
        } else {
          accountType = userInfo.isAquamarineMember ? 'isAquamarineMember' : 'isCrystalMember';
        }
      }

      let userInfoInfo = getData().main.userInfo;
      console.log('action.ts goldConinIndex userInfo', userInfo);
      userInfo = {
        ...userInfoInfo,
        ...userInfo,
        accountType,
      };

      console.log('action.ts userinfo', userInfo);

      // 会员则去获取每日赠送游戏
      if (accountType) {
        action.loadGameTimesDaily({delFlag: null});
      }

      // 查询是否是新人
      action.loadUserComputedGameTimes({});

      // 查询剩余游戏次数
      action.loadGameTimes({});

      // 查询当日剩余游戏次数
      action.loadGameDailyTimes();

      action.updateUserInfo(userInfo);

      action.commonChange('main.userInfo', {
        ...userInfo,
      });
      action.commonChange('main.response.loadUser', code);
      action.commonChange('main.status.loadingUser', false);
    },

    /**
     * 更新用户信息
     */
    async updateUserInfo(userInfo) {
      Taro.setStorageSync(GAME_STORAGE_INFO, userInfo);
    },

    /**
     * 查询用户的游戏的使用次数
     */
    async loadUserComputedGameTimes(payload) {
      action.commonChange('main.response.loadUserComputedGameTimes', '');
      action.commonChange('main.status.loadingUserComputedGameTimes', true);
      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, code, message} = await api.GoldCoinsController.userComputedGameTimes(params);
      console.log('action.ts loadUserComputedGameTimes data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        gameComputedTimes: data || 0,
      };

      console.log('action.ts loadUserComputedGameTimes', userInfo);

      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.loadUserComputedGameTimes', code);
      action.commonChange('main.status.loadingUserComputedGameTimes', false);
    },

    /**
     * 查询新人保障
     */
    async loadUserIsNewComer(payload) {
      console.log('action.tsx loadUserIsNewComer payload', payload);

      action.commonChange('main.response.isNewComer', '');
      action.commonChange('main.status.loadingIsNewComer', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.GoldCoinsController.userIsNewComer(params);
      console.log('action.ts loadUserIsNewComer data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        isNewComer: data,
      };

      console.log('action.ts userinFO', userInfo);

      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.isNewComer', code);
      action.commonChange('main.status.loadingIsNewComer', false);
    },

    /**
     * 查询每日游戏次数领取
     * @param payload
     */
    async loadGameTimesDaily(payload) {
      action.commonChange('main.gameReceiveInfo', {});
      action.commonChange('main.response.loadGameDaily', '');
      action.commonChange('main.status.loadingGameDaily', true);

      // 编辑参数
      let params = {
        gameType: GAME_TYPE,
        ...payload,
      };

      let {data, code, message} = await api.GoldCoinsController.getGameTimesReceiveDaily(params);

      let result = data
        ? {
            ...payload,
            ...data,
          }
        : {
            ...payload,
          };

      action.commonChange('main.gameReceiveInfo', result);
      action.commonChange('main.response.loadGameDaily', code);
      action.commonChange('main.status.loadingGameDaily', false);
    },

    /**
     * 查询游戏次数
     * @param payload
     */
    async loadGameTimes(payload) {
      action.commonChange('main.response.loadGameTimes', '');
      action.commonChange('main.status.loadingGameTimes', true);

      // 编辑参数
      let params = {
        gameType: GAME_TYPE,
        ...payload,
      };

      let {data, code, message} = await api.GoldCoinsController.getGameTimesConfigInfo(params);
      console.log('index.tsx getGameTimes data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        gameAvailableTimes: data || 0,
      };

      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.loadGameTimes', code);
      action.commonChange('main.status.loadingGameTimes', false);
    },

    /**
     * 查询游戏信息
     * @param payload
     */
    async loadGameInfo(payload) {
      action.commonChange('main.gameInfo', {});
      action.commonChange('main.response.loadGameInfo', '');
      action.commonChange('main.status.loadingGameInfo', true);

      // 编辑参数
      let params = {
        gameType: GAME_TYPE, //0-魔力金币雨，1-魔力抽盲盒，2-魔力赏，3-魔力抓娃娃，4-魔力抽抽卡，5-刮刮乐
      };

      let {data, code, message} = await api.GoldCoinsController.getGameIpConfigInfo(params);
      console.log('action.ts loadGameInfo data', data);
      data = data || {};

      let {
        main: {gameInfo},
      } = getData();
      gameInfo = {
        ...data,
        text: data.detail ? data.detail : '',
      };

      action.commonChange('main.gameInfo', gameInfo);
      action.commonChange('main.response.loadGameInfo', code);
      action.commonChange('main.status.loadingGameInfo', false);
    },

    /**
     * 查询当日游戏次数
     */
    async loadGameDailyTimes() {
      action.commonChange('main.response.loadGameDailyTimes', '');
      action.commonChange('main.status.loadingGameDailyTimes', true);

      // 编辑参数
      let payload = {
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.iplandBaseController.getGameDailyTimes(payload);
      console.log('goldCoinsIndex loadGameDailyTimes data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        userDailyTimes: data || 0,
      };
      console.log('action.ts loadGameDailyTimes=', userInfo);
      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.loadGameDailyTimes', code);
      action.commonChange('main.status.loadingGameDailyTimes', false);
    },

    /**
     * 查询任务列表
     */
    async loadTaskItems(payload) {
      action.commonChange('main.response.loadTask', '');
      action.commonChange('main.status.loadingTask', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE,
        // gameType: 0,// 暂时
      };

      let {data, code, message} = await api.GameTaskController.getTasksByGameType(params);
      console.log('loadTaskItems action data', data);

      let {
        main: {task},
      } = getData();

      action.commonChange('main.task', {
        ...task,
        items: data || [],
        page: {
          ...task.page,
        },
      });
      action.commonChange('main.response.loadTask', code);
      action.commonChange('main.status.loadingTask', false);
    },

    /**
     * 完成任务
     * @param payload
     */
    async computedTask(payload) {
      action.commonChange('main.response.computedTask', '');
      action.commonChange('main.status.computingTask', true);

      // 编辑参数
      let params = {
        ...payload,
      };
      let {data, code, message} = await api.GameTaskController.computedTask(params);
      action.commonChange('main.response.computedTask', code);
      action.commonChange('main.status.computingTask', false);
    },

    /**
     * 查询任务详情
     */
    async loadTaskDetailById(payload) {
      action.commonChange('main.response.loadTaskDetail', '');
      action.commonChange('main.status.loadingTaskDetail', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, code, message} = await api.GameTaskController.getTaskDetailById(params);
      console.log('loadTaskItems action data', data);

      let {
        main: {task},
      } = getData();

      action.commonChange('main.task', {
        ...task,
        detail: {
          ...(data || {}),
        },
      });
      action.commonChange('main.response.loadTaskDetail', code);
      action.commonChange('main.status.loadingTaskDetail', false);
    },

    /**
     * 查询榜单
     * @param payload
     */
    async loadRankingItems(payload) {
      action.commonChange('main.rankingItems', []);
      action.commonChange('main.rankingTopThreeItems', []);
      action.commonChange('main.rankingTopElseItems', []);
      action.commonChange('main.rankingSingledItems', []);
      action.commonChange('main.response.loadRank', '');
      action.commonChange('main.status.loadingRanking', true);

      // 编辑参数
      let params = {
        ...payload,
        type: RANKING_TYPE[1], //魔力豆榜单
        sortRole: 'desc', // 排序规则 降序排序
      };

      let {data, code, message} = await api.GoldCoinsController.getRankingItems(params);
      console.log('action.ts goldCoinindex  loadRankingItems data', data, 'code', code);

      let items = data || [];
      let topThreeItems = []; // 前三名
      let topElseItems = []; // 前四-前六
      let singledItems = []; // 未上榜单

      if (items.length > 0) {
        topThreeItems = items.filter((i, index) => i.ranking > 0 && i.ranking < 4);
        singledItems = [items[0]]; // 暂无上榜单（自己）
        topElseItems = items.slice(4);
      }

      action.commonChange('main.rankingItems', items);
      action.commonChange('main.rankingTopThreeItems', topThreeItems);
      action.commonChange('main.rankingTopElseItems', topElseItems);
      action.commonChange('main.rankingSingledItems', singledItems);
      action.commonChange('main.response.loadRank', code);
      action.commonChange('main.status.loadingRanking', false);
    },

    /**
     * 查询游戏配置信息（物品）
     * @param payload
     */
    async loadGameGrticleInfo(payload) {
      console.log('goldIndex loadGameCrticleInfo payload', payload);

      action.commonChange('main.gameCrticleInfo', {});
      action.commonChange('main.response.loadGameGrticle', '');
      action.commonChange('main.status.loadingGameGrticle', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, code, message} = await api.GoldCoinsController.getGameGrticleInfo(params);
      console.log('goldCoinIndex loadGameGrticleInfo data', data);

      action.commonChange('main.gameCrticleInfo', data || {});
      action.commonChange('main.response.loadGameGrticle', '');
      action.commonChange('main.status.loadingGameGrticle', true);
    },

    /**
     * 查询道具信息
     */
    async loadPropItems(payload) {
      action.commonChange('main.response.loadProp', '');
      action.commonChange('main.status.loadingProp', true);

      // 编辑参数
      let params = {
        // ...payload,
        prizeType: GAME_RPICE_TYPE['prop'],
        status: PROP_STAUTS['UNUSE'],
      };

      let {data, code, message} = await api.GamePropController.getMyProp(params);
      console.log('action.ts loadProp data', data);
      data = data || [];

      // 重组数据
      let result = [];
      if (data.length > 0) {
        data.map((i) => {
          i.propVO = i.propVO || {};
          result.push({
            ...i,
            propImg: i.propVO.imgUrl,
            propName: i.propVO.propName,
            propEndTime: i.propVO.endTime,
            propDesc: i.propVO.propDesc,
            ruleType: i.propVO.ruleType,
            ruleValue: i.propVO.ruleValue || 0,
            propStartTime: i.propVO.startTime,
          });
        });
      }

      let {
        main: {prop},
      } = getData();

      action.commonChange('main.prop', {
        ...prop,
        items: result || [],
        page: {
          ...prop.page,
        },
      });
      action.commonChange('main.response.loadProp', code);
      action.commonChange('main.status.loadingProp', false);
    },

    /**
     * 判断能否使用道具
     * @param payload
     */
    async usePropPossibility(payload) {
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.response.usePropPossibility', '');
      action.commonChange('main.status.usingPropPossibility', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.GamePropController.useProp(params);
      console.log('action.ts usePropPossibility data', data);

      action.commonChange('main.response.usePropPossibility', code);
      action.commonChange('main.codeMessage', message);
      action.commonChange('main.status.usingPropPossibility', false);
    },

    /**
     * 非会员赠送游戏 （金币雨专属）
     * @returns
     */
    async giveUserNoVipGameTimes() {
      action.commonChange('main.response.giveGameTimes', '');
      action.commonChange('main.status.givingGameTimes', true);

      // 编辑参数
      let params = {
        gameType: GAME_TYPE, // 金币雨
      };
      let {data, code, message} = await api.GoldCoinsController.giveGameTimesNoVip(params);
      console.log('action.ts giveUserNoVipGameTimes data', data);

      action.commonChange('main.response.giveGameTimes', code);
      action.commonChange('main.status.givingGameTimes', false);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageGoldCoinsIndexPaMain'),
  };
}
